// controller/article.js
"use strict";
const Controller = require("egg").Controller;
const moment = require("moment");
class ArticleController extends Controller {
  // 创建文章
  async newArticle() {
    const { ctx } = this;
    ctx.logger.info("创建文章参数", ctx.request.body);
    const data = {
      ...ctx.request.body,
      create_time: moment().format("YYYY-MM-DD HH:mm:ss"),
      status: ctx.request.body.status == undefined ? 0 : ctx.request.body.status,
      topping: ctx.request.body.topping == undefined ? 0 : ctx.request.body.topping,
      allow_comment: ctx.request.body.allow_comment == undefined ? 0 : ctx.request.body.allow_comment,
      deleted: 0
    };
    const result = await ctx.service.article.newArticle(data);
    console.log("result", result);
    if (!result) {
      ctx.body = {
        code: 500,
        message: "创建失败",
        success: false,
      };
      return;
    }
    ctx.body = {
      code: 200,
      message: "创建成功",
      success: true,
    };
  }
  // 删除文章
  async deleteArticle() {
    const { ctx } = this;
    ctx.logger.info("删除文章参数", ctx.request.body);
    const { id } = ctx.request.body;
    const result = await ctx.service.article.deleteArticle(id);
    console.log("result", result);
    if (!result) {
      ctx.body = {
        code: 500,
        message: "删除失败",
        success: false,
      };
      return;
    }
    ctx.body = {
      code: 200,
      message: "删除成功",
      success: true,
    };
  }
  // 更新文章
  async updateArticle() {
    const { ctx } = this;
    ctx.logger.info("更新文章参数", ctx.request.body);
    const data = ctx.request.body;
    const result = await ctx.service.article.updateArticle(data);
    console.log("result", result);
    if (!result || result.changedRows == 0) {
      ctx.body = {
        code: 500,
        message: "更新失败",
        success: false,
      };
      return;
    }
    ctx.body = {
      code: 200,
      message: "更新成功",
      success: true,
    };
  }
  // 文章列表
  async getArticleList() {
    const { ctx } = this;
    ctx.logger.info("文章列表参数", ctx.request.query);
    const data = ctx.request.query;
    const result = await ctx.service.article.getArticleList(data);
    console.log("result", result);
    if (!result) {
      ctx.body = {
        code: 500,
        message: "查询失败",
        success: false,
      };
      return;
    }
    ctx.body = result;
  }
  // 文章详情
  async getArticleDetail() {
    const { ctx } = this;
    ctx.logger.info("文章详情参数", ctx.request.query);
    const { id } = ctx.request.query;
    const result = await ctx.service.article.getArticleDetail(id);
    console.log("result", result);
    if (!result) {
      ctx.body = {
        code: 500,
        message: "查询失败",
        success: false,
      };
      return;
    }
    ctx.body = {
      code: 200,
      success: true,
      data: result,
    };
  }
}

module.exports = ArticleController;
